<template>
	<div>
		<el-form ref="loginForm" :model="form" :rules="rules" label-width="0" size="large">
			<el-form-item prop="user">
				<el-input v-model="form.user" prefix-icon="el-icon-user" clearable
					:placeholder="$t('login.userPlaceholder')">
					<template #append>
						<el-select v-model="userType" style="width: 130px;">
							<el-option :label="$t('login.admin')" value="admin"></el-option>
							<el-option :label="$t('login.user')" value="user"></el-option>
						</el-select>
					</template>
				</el-input>
			</el-form-item>
			<el-form-item prop="password">
				<el-input v-model="form.password" prefix-icon="el-icon-lock" clearable show-password
					:placeholder="$t('login.PWPlaceholder')"></el-input>
			</el-form-item>
			<el-form-item style="margin-bottom: 10px;">
				<el-col :span="12">
					<el-checkbox :label="$t('login.rememberMe')" v-model="form.autologin"></el-checkbox>
				</el-col>
				<el-col :span="12" class="login-forgot">
					<router-link to="/reset_password">{{ $t('login.forgetPassword') }}？</router-link>
				</el-col>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" style="width: 100%;" :loading="islogin" round @click="lian">{{
						$t('login.signIn')
				}}</el-button>
			</el-form-item>
			<div class="login-reg">
				{{ $t('login.noAccount') }} <router-link to="/user_register">{{ $t('login.createAccount')
				}}</router-link>
			</div>
		</el-form>
		<!-- 人脸识别弹出框 -->
		<el-dialog v-model="this.dialogVisible" title="人脸验证" width="30%" :before-close="handleClose">
			<div>
				<canvas style="display: none" id="canvasCamera" :width="videoWidth" :height="videoHeight"></canvas>
				<div class="imgs">
					<video id="videoCamera" :width="videoWidth" :height="videoHeight" autoplay class="img"></video>
				</div>
				<div class="paizhao">
					<el-button class="but" @click="getCompetence()" type="primary" plain>打开摄像头</el-button>
					<el-button class="but" @click="setImage()" type="primary" plain>拍照</el-button>
				</div>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="this.dialogVisible = false">Cancel</el-button>
					<el-button type="primary" @click="huoq">
						验证并登录
					</el-button>
				</span>
			</template>
		</el-dialog>
	</div>

</template>

<script>
import router from '@/router/router'
import axios from 'axios'
// console.log(rs);
export default {
	data() {
		return {
			videoWidth: 200,
			videoHeight: 200,
			imgSrc: "",
			thisCancas: null,
			thisContext: null,
			thisVideo: null,
			openVideo: false,
			dialogVisible: false,
			userType: 'admin',
			form: {
				user: "admin",
				password: "admin",
				autologin: false
			},
			mysqlform: {
				id: '',
				images: "",
				ImageA: "",
				ImageB: "",
			},
			rules: {
				user: [
					{ required: true, message: this.$t('login.userError'), trigger: 'blur' }
				],
				password: [
					{ required: true, message: this.$t('login.PWError'), trigger: 'blur' }
				]
			},
			islogin: false,
		}
	},
	watch: {
		userType(val) {
			if (val == 'admin') {
				this.form.user = 'admin'
				this.form.password = 'admin'
			} else if (val == 'user') {
				this.form.user = 'user'
				this.form.password = 'user'
			}
		}
	},
	mounted() {

	},
	methods: {
		// 打开摄像头
		getCompetence() {
			var _this = this;
			_this.thisCancas = document.getElementById("canvasCamera");
			_this.thisContext = this.thisCancas.getContext("2d");
			_this.thisVideo = document.getElementById("videoCamera");
			_this.thisVideo.style.display = "block";
			// 获取媒体属性，旧版本浏览器可能不支持mediaDevices，我们首先设置一个空对象
			if (navigator.mediaDevices === undefined) {
				navigator.mediaDevices = {};
			}
			// 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
			// 使用getUserMedia，因为它会覆盖现有的属性。
			// 这里，如果缺少getUserMedia属性，就添加它。
			if (navigator.mediaDevices.getUserMedia === undefined) {
				navigator.mediaDevices.getUserMedia = function (constraints) {
					// 首先获取现存的getUserMedia(如果存在)
					var getUserMedia =
						navigator.webkitGetUserMedia ||
						navigator.mozGetUserMedia ||
						navigator.getUserMedia;
					// 有些浏览器不支持，会返回错误信息
					// 保持接口一致
					if (!getUserMedia) {
						//不存在则报错
						return Promise.reject(
							new Error("getUserMedia is not implemented in this browser")
						);
					}
					// 否则，使用Promise将调用包装到旧的navigator.getUserMedia
					return new Promise(function (resolve, reject) {
						getUserMedia.call(navigator, constraints, resolve, reject);
					});
				};
			}
			var constraints = {
				audio: false,
				video: {
					width: this.videoWidth,
					height: this.videoHeight,
					transform: "scaleX(-1)",
				},
			};
			navigator.mediaDevices


				.getUserMedia(constraints)
				.then(function (stream) {
					// 旧的浏览器可能没有srcObject
					if ("srcObject" in _this.thisVideo) {
						_this.thisVideo.srcObject = stream;
					} else {
						// 避免在新的浏览器中使用它，因为它正在被弃用。
						_this.thisVideo.src = window.URL.createObjectURL(stream);
					}
					_this.thisVideo.onloadedmetadata = function () {
						_this.thisVideo.play();
					};
				})
				.catch((err) => {
					console.log(err);
				});
		},
		//  绘制图片（拍照功能）
		setImage() {
			var _this = this;
			// canvas画图
			_this.thisContext.drawImage(
				_this.thisVideo,
				0,
				0,
				_this.videoWidth,
				_this.videoHeight
			);
			// 获取图片base64链接
			console.log(this.thisCancas, 1961565)
			var image = this.thisCancas.toDataURL("image/png");
			this.mysqlform.images = image; //赋值并预览图片
			this.mysqlform.ImageB = image; //赋值并预览图片
			this.$message({ showClose: true, message: '捕获成功', type: 'success' });
		},
		// 获取用户照片编码
		async GetLogin(i) {
			var z = await axios.get(`http://127.0.0.1:8000/face?search=${i}`)
			if (z.status == 200) {
				this.mysqlform.id = z.data[0].id
				this.mysqlform.ImageA = z.data[0].images
				this.Getdl()
			}else{
				this.$message('请露出全脸');
			}
		},
		// 关闭人脸识别弹框
		handleClose(done) {
			this.ElMessageBox.confirm('确定要关闭?')
				.then(() => {
					done()
				})
				.catch(() => {
					// catch error
				})
		},
		// 打开人脸识别弹框
		lian() {
			this.dialogVisible = true
		},
		// 验证账号密码
		async huoq() {
			let {user,password}=this.form
			let z = await axios.post(`http://127.0.0.1:8000/user`, {'username':user,password})
			console.log(z);
			if (z.data.status == 200) {
				// 获取用户名/ID
				this.GetLogin(this.form.user)
			} else {
				this.$message.error('用户名或密码错误');
			}
		},
		// 人脸识别登录接口
		async Getdl() {
			this.dialogVisible = false
			let { ImageB, ImageA,id } = this.mysqlform
			// let { user, password } = this.form
			await axios.post(`http://127.0.0.1:8000/login`, { ImageB, ImageA,id }).then(()=>{this.login()}).catch((err)=>{
					if(err){
						this.$message.error('非本人登录，本网站拒绝访问');
					}
				})
		},
		// 登录scui接口
		async login() {

			var validate = await this.$refs.loginForm.validate().catch(() => { })
			if (!validate) { return false }

			this.islogin = true
			var data = {
				username: this.form.user,
				password: this.$TOOL.crypto.MD5(this.form.password)
			}
			//获取token
			var user = await this.$API.auth.token.post(data)
			if (user.code == 200) {
				this.$TOOL.cookie.set("TOKEN", user.data.token, {
					expires: this.form.autologin ? 24 * 60 * 60 : 0
				})
				this.$TOOL.data.set("USER_INFO", user.data.userInfo)
			} else {
				this.islogin = false
				this.$message.warning(user.message)
				return false
			}
			//获取菜单
			var menu = null
			if (this.form.user == 'admin') {
				menu = await this.$API.system.menu.myMenus.get()
				console.log(menu, 123);
			} else {
				menu = await this.$API.demo.menu.get()
			}
			if (menu.code == 200) {
				if (menu.data.menu.length == 0) {
					this.islogin = false
					this.$alert("当前用户无任何菜单权限，请联系系统管理员", "无权限访问", {
						type: 'error',
						center: true
					})
					return false
				}
				console.log(menu.data.menu, 123);
				this.$TOOL.data.set("MENU", [menu.data.menu[0], ...router])
				this.$TOOL.data.set("PERMISSIONS", menu.data.permissions)
			} else {
				this.islogin = false
				this.$message.warning(menu.message)
				return false
			}
			console.log(123);
			this.$router.replace({


				path: '/member/corporate'
			})
			this.$message.success("Login Success 登录成功")
			this.islogin = false
		},
	}
}
</script>

<style>

</style>
